package controllers

import (
	"github.com/astaxie/beego"
	"helloCms/models"
	"github.com/astaxie/beego/orm"
	"time"
	"strings"
	"strconv"
)

type RoleInfoController struct {
	beego.Controller
}

func (c *RoleInfoController) Index() {
	c.TplName = "RoleInfo/Index.html"
}

func (c *RoleInfoController) ShowAddRole() {
	c.TplName = "RoleInfo/ShowAddRole.html"
}

func (c *RoleInfoController) GetRoleInfo() {
	pageIndex, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("rows")
	start := (pageIndex - 1) * pageSize
	roles := make([]models.Roleinfo, 0)

	o := orm.NewOrm()
	o.QueryTable("roleinfo").Filter("del_flag", 0).OrderBy("id").Limit(pageSize, start).All(&roles)
	count, _ := o.QueryTable("roleinfo").Filter("del_flag", 0).Count()

	c.Data["json"] = map[string]interface{}{"rows": roles, "total": count}
	c.ServeJSON()
}

func (c *RoleInfoController) AddRole() {
	roleInfo := models.Roleinfo{
		RoleName:  c.GetString("roleName"),
		Remark:    c.GetString("roleRemark"),
		ModifDate: time.Now(),
		AddDate:   time.Now(),
		DelFlag:   0,
	}

	o := orm.NewOrm()
	_, err := o.Insert(&roleInfo)
	if err == nil {
		c.Data["json"] = map[string]interface{}{"flag": "ok"}
	} else {
		c.Data["json"] = map[string]interface{}{"flag": "no"}
	}
	c.ServeJSON()
}

func (c *RoleInfoController) DeleteRole() {
	ids := strings.Split(c.GetString("id"), ",")
	o := orm.NewOrm()
	role := models.Roleinfo{}
	for _, id := range ids {
		role.Id, _ = strconv.Atoi(id)
		o.Read(&role)
		role.DelFlag = 1
		o.Update(&role)
	}
	c.Data["json"] = map[string]interface{}{"flag": "ok"}
	c.ServeJSON()
}

func (c *RoleInfoController) ShowSetRoleAction() {
	roleId, _ := c.GetInt("id")
	role := models.Roleinfo{Id: roleId}
	o := orm.NewOrm()
	o.Read(&role)
	o.LoadRelated(&role, "Actions")

	allActions := make([]models.Actioninfo, 0)
	o.QueryTable("actioninfo").Filter("del_flag", 0).OrderBy("Id").All(&allActions)
	c.Data["roleInfo"] = role
	c.Data["allActions"] = allActions
	c.Data["roleExtActions"] = role.Actions
	c.TplName = "RoleInfo/ShowSetRoleAction.html"
}

func (c *RoleInfoController) SetRoleAction() {
	roleId, _ := c.GetInt("roleId") //获取角色ID

	allKeys := c.Ctx.Request.PostForm //获取所有选中的权限ID
	actionIdList := make([]int, 0)
	for k, _ := range allKeys { //获取checkbox选中的权限ID
		if strings.Contains(k, "cba_") {
			k = strings.Replace(k, "cba_", "", -1)
			id, _ := strconv.Atoi(k)
			actionIdList = append(actionIdList, id)
		}
	}
	o := orm.NewOrm()
	role := models.Roleinfo{Id: roleId}
	o.LoadRelated(&role, "Actions")
	m2m := o.QueryM2M(&role, "Actions")
	o.Begin()
	var (
		err1 error
		err2 error
	)
	for _,act:=range role.Actions{
		_,err1=m2m.Remove(act)
	}
	action:=models.Actioninfo{}
	for _,actId:=range actionIdList{
		action.Id=actId
		o.Read(&action)
		_,err2=m2m.Add(&action)
	}
	if err1!=nil||err2!=nil{
		o.Rollback()
		c.Data["json"]=map[string]interface{}{"flag":"no"}
	}
	o.Commit()
	c.Data["json"]=map[string]interface{}{"flag":"ok"}
	c.ServeJSON()
}
